package org.hilo.boot.app.component;

import java.util.List;

import org.jretty.apibase.Result;
import org.hilo.boot.core.UT;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Spring Response Body Advice
 * @see ResponseBodyAdvice
 * 
 * @author zollty
 * @since 2018-2-23
 */
@RestControllerAdvice
@ConditionalOnProperty(name = "hilo.web.enable-i18n", havingValue = "true")
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public Object beforeBodyWrite(Object resultValue, 
            MethodParameter returnType, MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType, 
            ServerHttpRequest request, ServerHttpResponse response) {

        if(resultValue instanceof Result) {
            Result<?> result = (Result<?>) resultValue;
            HttpHeaders headers = response.getHeaders();
            List<String> list = headers.get("locale");
            String locale = null;
            if (UT.Coll.isNotEmpty(list)) {
                locale = list.get(0);
                headers.remove("locale");
                result.setLocale(locale);
            }
        }

        return resultValue;
    }

    @Override
    public boolean supports(MethodParameter arg0, 
            Class<? extends HttpMessageConverter<?>> arg1) {
        // Do Nothing.
        return true;
    }

}
